package com.haidechizi.validate.constraint;

import com.haidechizi.validate.annotation.DictCheck;
import com.haidechizi.validate.holder.DictHolder;
import org.springframework.util.StringUtils;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.Set;

public class DictCheckConstraintValidator implements ConstraintValidator<DictCheck, String> {

    private Set<String> values;
    private boolean required;

    @Override
    public void initialize(DictCheck dictCheck) {
        String value = dictCheck.value();
        this.values = DictHolder.getValues(value);
        this.required = dictCheck.required();
    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext constraintValidatorContext) {
        if (!required) {
            if (StringUtils.isEmpty(value)) {
                return true;
            }
        }
        if (values.contains(value)) {
            return true;
        }
        return false;
    }
}
